#!/bin/bash
#
#node-blog centos init script v0.1
#
#install epel repo
#install mysql redis
yum install epel-* wget git -y
yum install mysql-server mysql-devel mysql redis nginx -y

#install node.js
if [ "`uname -m`" == "x86_64" ]; then
	if [ ! -f node-v0.12.4-linux-x64.tar.gz ]; then
	wget http://nodejs.org/dist/v0.12.4/node-v0.12.4-linux-x64.tar.gz
	fi	
	tar -zxf node-v0.12.4-linux-x64.tar.gz
	if [ -d /usr/local/node ];then
		mv /usr/local/node /usr/local/node`date +%Y%m%d`
		mv node-v0.12.4-linux-x64 /usr/local/node
	else
		mv node-v0.12.4-linux-x64 /usr/local/node
	fi
elif [ "`uname -m`" == "i686" ]; then

	if [ ! -f node-v0.12.4-linux-x86.tar.gz ]; then
	wget http://nodejs.org/dist/v0.12.4/node-v0.12.4-linux-x86.tar.gz
	fi	
	tar -zxf node-v0.12.4-linux-x86.tar.gz
	if [ -d /usr/local/node ];then
		mv /usr/local/node /usr/local/node`date +%Y%m%d`
		mv node-v0.12.4-linux-x86 /usr/local/node
	else
		mv node-v0.12.4-linux-x86 /usr/local/node
	fi
fi

#config
echo 'NODE_HOME=/usr/local/node' >/etc/profile.d/node_path.sh
echo 'export PATH=$PATH:$NODE_HOME/bin' >>/etc/profile.d/node_path.sh
source /etc/profile

if [ ! -f /var/log/mysql_ok ];then
	/etc/init.d/mysqld restart
	chkconfig mysqld on
	/usr/bin/mysqladmin -uroot password root
	/usr/bin/mysql -uroot -proot -e "create database node_blog;"
	touch /var/log/mysql_ok
fi

if [ ! -f /var/log/redis_ok ];then
	/etc/init.d/redis restart
	chkconfig redis on
	touch /var/log/redis_ok
fi

if [ ! -f /var/log/pm2_ok ];then
	/usr/local/node/bin/npm install pm2 -g
	if [ -f /usr/local/node/bin/pm2 ];then
		/usr/local/node/bin/pm2 startup centos
		touch /var/log/pm2_ok
	fi
fi

if [ ! -f /var/log/nginx_ok ];then
	\cp -a /etc/nginx/conf.d /etc/nginx/`date +%Y%m%d`
	rm -rf /etc/nginx/conf.d/*
	curl https://raw.githubusercontent.com/akin520/AutoSetup/master/proxy.conf -o /etc/nginx/conf.d/node-blog.conf
	sed -i 's/127.0.0.1:80/127.0.0.1:3001/g' /etc/nginx/conf.d/node-blog.conf
	/etc/init.d/nginx restart
	chkconfig nginx on
	touch /var/log/nginx_ok
fi

